package Util;

import Dao.Impl.TransactionDAOImpl;
import Dao.Impl.UserDAOImpl;
import Model.Transaction;
import Model.User;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

public class ReportGenerator {
    private static final Logger logger = LogManager.getLogger(ReportGenerator.class);

    private Connection connection;
    private UserDAOImpl userDAO;
    private TransactionDAOImpl transactionDAO;

    public ReportGenerator() {
        try {
            connection = DbConnector.getConnection();
            userDAO = new UserDAOImpl();
            transactionDAO = new TransactionDAOImpl();
        } catch (SQLException e) {
            logger.error("数据库连接失败: {}", e.getMessage());
            System.exit(1);
        }
    }

    public void generateUserDataReport() {
        logger.info("正在生成用户数据报表...");

        User[] users = userDAO.getAllUser();

        if (users.length > 0) {
            // 获取桌面路径
            String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
            String datePart = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
            String fileName = desktopPath + File.separator + datePart + "_用户信息报表.xlsx";

            Workbook workbook = new XSSFWorkbook();
            Sheet sheet = workbook.createSheet(datePart + "用户数据");

            // 创建表头
            Row headerRow = sheet.createRow(0);
            String[] headers = {"序号", "用户名", "联系信息", "余额", "账户状态"};
            for (int i = 0; i < headers.length; i++) {
                Cell cell = headerRow.createCell(i);
                cell.setCellValue(headers[i]);
            }

            // 手动设置列宽
            sheet.setColumnWidth(0, 5 * 256);  // 序号列
            sheet.setColumnWidth(1, 15 * 256); // 用户名列
            sheet.setColumnWidth(2, 20 * 256); // 联系信息列
            sheet.setColumnWidth(3, 10 * 256); // 余额列
            sheet.setColumnWidth(4, 10 * 256); // 账户状态列

            // 填充用户数据
            for (int i = 0; i < users.length; i++) {
                Row row = sheet.createRow(i + 1);

                row.createCell(0).setCellValue(i + 1); // 序号
                row.createCell(1).setCellValue(users[i].getUsername());
                row.createCell(2).setCellValue(users[i].getContactInfo());

                Cell balanceCell = row.createCell(3);
                balanceCell.setCellValue(users[i].getBalance());

                Cell statusCell = row.createCell(4);
                boolean user_status = users[i].isFrozen() == 1;
                statusCell.setCellValue(user_status ? "已冻结" : "正常");
            }

            // 保存工作簿
            try (FileOutputStream fos = new FileOutputStream(fileName)) {
                workbook.write(fos);
                logger.info("用户数据报表已生成: {}", fileName);
            } catch (IOException e) {
                logger.error("保存报表文件时出错: {}", e.getMessage());
            }
        } else {
            logger.warn("没有用户信息可生成报表。");
            System.out.println("没有用户信息可生成报表。");
        }
    }

    @SuppressWarnings("resource")
    public void generateTransactionHistoryReport(User user) {
        try {
            logger.info("正在生成{}交易历史报表...", user.getUsername());

            // 获取用户交易记录
            int userId = user.getId();
            List<Transaction> transactions = transactionDAO.getTransactionsByUserId(userId);

            if (transactions != null && !transactions.isEmpty()) {
                // 获取桌面路径
                String desktopPath = System.getProperty("user.home") + File.separator + "Desktop";
                String datePart = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
                String username = user.getUsername();
                String fileName = desktopPath + File.separator + datePart + "_" + username + "_交易历史报表.xlsx";

                Workbook workbook = new XSSFWorkbook();
                Sheet sheet = workbook.createSheet(datePart + "交易历史");

                // 创建表头
                Row headerRow = sheet.createRow(0);
                String[] headers = {"序号", "交易类型", "金额", "总余额", "交易时间", "描述"};
                for (int i = 0; i < headers.length; i++) {
                    Cell cell = headerRow.createCell(i);
                    cell.setCellValue(headers[i]);
                }

                // 手动设置列宽
                sheet.setColumnWidth(0, 5 * 256);  // 序号列
                sheet.setColumnWidth(1, 15 * 256); // 交易类型列
                sheet.setColumnWidth(2, 10 * 256); // 金额列
                sheet.setColumnWidth(3, 10 * 256); // 总余额列
                sheet.setColumnWidth(4, 20 * 256); // 交易时间列
                sheet.setColumnWidth(5, 30 * 256); // 描述列

                // 填充交易数据
                for (int i = 0; i < transactions.size(); i++) {
                    Transaction transaction = transactions.get(i);
                    Row row = sheet.createRow(i + 1);

                    row.createCell(0).setCellValue(i + 1); // 序号
                    row.createCell(1).setCellValue(transaction.getTransactionType());
                    row.createCell(2).setCellValue(transaction.getAmount());
                    row.createCell(3).setCellValue(transaction.getTotalBalance());
                    SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    dateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
                    row.createCell(4).setCellValue(dateFormat.format(transaction.getTransactionDate()));
                    row.createCell(5).setCellValue(transaction.getDescription());
                }

                // 保存工作簿
                try (FileOutputStream fos = new 
                        FileOutputStream(fileName)) {
                    workbook.write(fos);
                    logger.info("交易历史报表已生成: {}", fileName);
                } catch (IOException e) {
                    logger.error("保存报表文件时出错: {}", e.getMessage());
                }
            } else {
                logger.warn("没有交易记录可生成报表。");
            }
        } catch (Exception e) {
            logger.error("生成交易历史报表失败: {}", e.getMessage());
        }
    }
}